package config

import (
	"fmt"

	"gopkg.in/ini.v1"
)

// var loggerl = logger.InitLog()

type Config struct {
	DataBase Database
	Server   Server
	Log      Log
	Type     Type
}
type Database struct {
	DRIVER string `ini:"DRIVER"`
	SERVER string `ini:"SERVER"`
	PORT   string `ini:"PORT"`
	UID    string `ini:"UID"`
	PWD    string `ini:"PWD"`
	DB     string `ini:"DB"`
}
type Server struct {
	ServerPort string `ini:"ServerPort"`
	TimeOut    int    `ini:"timeout"`
}

type Log struct {
	LogLevel string `ini:"LogLevel"`
}

type Type struct {
	Ltype string `ini:"ltype"`
}

func GetConfig() (structModel Config, error error) {
	cfg, err := ini.Load("config.ini")
	if err != nil {
		// loggerl.Error("Error loading config:", err)
		return structModel, err
	}

	c := Config{}
	cfg.MapTo(&c)
	// t := reflect.TypeOf(c)
	// for i := 0; i < t.NumField(); i++ {
	// field := t.Field(i)
	// value := reflect.ValueOf(c).FieldByName(field.Name).Interface()
	// loggerl.Info(fmt.Sprintf("%s: %v", field.Name, value))
	// }
	return c, nil
}

func LoadServer() string {
	c, err := GetConfig()
	if err != nil {
		// loggerl.Error("Error loading config:", err)
		return ""
	}
	return c.Server.ServerPort
}

func LoadDB() string {
	c, err := GetConfig()
	if err != nil {
		// loggerl.Error("Error loading config:", err)
		return ""
	}
	// loggerl.Debug(fmt.Sprintf("Starting AcsGo %s", c.Server.ServerPort))
	// connStr := fmt.Sprintf("DRIVER={%s};SERVER=%s;PORT=%s;DATABASE=%s;UID=%s;PWD=%s;encrypt=disable", c.DataBase.DRIVER, c.DataBase.SERVER, c.DataBase.PORT, c.DataBase.DB, c.DataBase.UID, c.DataBase.PWD)
	connStr := fmt.Sprintf("DRIVER={%s};server=%s;port=%s;database=%s;UID=%s;password=%s;encrypt=disable", c.DataBase.DRIVER, c.DataBase.SERVER, c.DataBase.PORT, c.DataBase.DB, c.DataBase.UID, c.DataBase.PWD)

	return connStr
}

func GetDb() *Database {
	c, err := GetConfig()
	if err != nil {
		// loggerl.Error("Error loading config:", err)
		return nil
	}
	return &c.DataBase
}
func LoadLogLevel() string {
	c, err := GetConfig()
	if err != nil {
		// loggerl.Error("Error loading config:", err)
		return ""
	}
	return c.Log.LogLevel
}

func LoadType() string {
	c, err := GetConfig()
	if err != nil {
		// loggerl.Error("Error loading config:", err)
		return ""
	}
	return c.Type.Ltype
}
